package com.ln.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ln.yygh.cmn.Dict;
import com.ln.yygh.cmn.listenr.DictListenr;
import com.ln.yygh.cmn.mapper.DictMapper;
import com.ln.yygh.cmn.service.DictService;
import com.ln.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author: lianXiaoChen
 * @create: 2021-05-25 15:20
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count > 0;
    }

    //实现数据字典导出
    @Override
    public void exporDiceData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");//防止中文乱码  和easyexcel没关系
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment:filename=" + fileName + ".xlsf");
        //查询数据库
        List<Dict> dicts = baseMapper.selectList(null);
        List<DictEeVo> list = new ArrayList<>();
        for (Dict d : dicts) {
            DictEeVo vo = new DictEeVo();
            BeanUtils.copyProperties(d, vo);//调用工具类把信息循环添加
            list.add(vo);
        }
        //调用方法进行操作
        //我们要将dice转换为DictEeVo
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 信息导入
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),
                    DictEeVo.class,
                    new DictListenr(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //工具类根据dictCode查询用户信息
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        return baseMapper.selectOne(wrapper);
    }
    //根据value和sictCode查询用户信息
    @Override
    public String getDictName(String dictCode, String value) {
        //因为dictCode=null 则直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            //diceCode不为空 则根据dictCode和value值查询，
            // 先根据dictCode查询dict对象 在得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long id = codeDict.getId();
            //根据这个id和value查询
            Dict findDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", id)
                    .eq("value", value));
            return findDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //现根据dictCode获取id
        Dict dict = this.getDictByDictCode(dictCode);
        //根据id获取信息
        return  this.findChlidData(dict.getId());
    }

}
